/**
 * 
 */
package json.taobao.action;

import json.item.Item;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.FileItem;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemAddRequest;
import com.taobao.api.request.ItemDeleteRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItempropsGetRequest;
import com.taobao.api.request.ItemsGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.ProductsGetRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.ItemAddResponse;
import com.taobao.api.response.ItemDeleteResponse;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItempropsGetResponse;
import com.taobao.api.response.ItemsGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.ProductsGetResponse;
import com.taobao.api.response.UserGetResponse;

/**
 * @author Administrator 淘宝动作类，集中了和淘宝交互动作的类
 */
public class Actions {
	String url = "http://gw.api.tbsandbox.com/router/rest";
	String appkey = "12277545";// 12277545 //12232777
	String secret ="sandbox4b9089895943bd89cad10154e";// "sandbox4b9089895943bd89cad10154e";// "sandboxe090d9019eba130342d995ea7";
	String session = "4061130aa2e798aa5f20fe1818181bf69f6deqR0albTc311800065581";
	TaobaoClient client;

	public Actions(String url, String appkey, String secret, String session) {
		this.url = url;
		this.appkey = appkey;
		this.secret = secret;
		this.session = session;
		client = new DefaultTaobaoClient(url, appkey, secret);// 实例化TopClient类
	}

	/**
	 * 列出某用户的产品
	 * 
	 * @return
	 * @throws ApiException
	 */
	public String ProductsGetRequest() throws ApiException {
		ProductsGetRequest req = new ProductsGetRequest();
		req.setFields("product_id,cat_name,sale_props_str");
		// req2.setFields("product_id,cid,cat_name,props,props_str,name,binds,binds_str,sale_props,sale_props_str,price,desc,pic_url,created,modified,product_img.id,product_img.url,product_img.position,product_prop_img.id,product_prop_img.props,product_prop_img.url,product_prop_img.position");
		req.setNick("liuxiaozheng012");
		req.setPageSize(20l);
		// req2
		ProductsGetResponse response = client.execute(req, session);
		System.out.println("result:" + response.getBody());
		return response.getBody();
	}

	/**
	 * 获得商品
	 * 
	 * @return
	 * @throws ApiException
	 */
	public String ItemsGetRequest() throws ApiException {
		ItemsGetRequest req = new ItemsGetRequest();
		req.setFields("iid,title,nick");
		// req7.setQ("N97");
		req.setNicks("liuxiaozheng012");
		ItemsGetResponse response = client.execute(req);
		System.out.println("result:" + response.getBody());
		System.out.println("result:" + response.getItems());
		return response.getBody();
	}

	/**
	 * 这个是搜索引擎的接口，查询商品是有15分钟左右的延时的，建议使用taobao.items.onsale.get或者taobao.item.
	 * get查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public String ItemsOnsaleGetRequest() throws Exception {
		ItemsOnsaleGetRequest req14 = new ItemsOnsaleGetRequest();
		req14.setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		// / req14.setQ("hahah999");
		// req14.setCid(110209L);
		ItemsOnsaleGetResponse response = client.execute(req14);
		System.out.println("onsale items=" + response.getBody());
		return response.getBody();
	}

	/**
	 * 添加商品
	 * 
	 * @return
	 * @throws Exception
	 */
	public String ItemAddRequest(Item item) throws Exception {
		ItemAddRequest req = new ItemAddRequest();
	/*	req.setNum(2L);
		req.setPrice("111");
		req.setType("fixed");
		req.setStuffStatus("new");
		req.setTitle("hahah999");

		// req8.setImage(new
		// FileItem("http://img04.tbsandbox.com/bao/uploaded/i4/T1updXXe..4t1e17oY_030240.jpg"));
		req.setImage(new FileItem("D:\\tempt\\gwt-logo.png"));
		req.setDesc("<a>asjfdljasf</a><b>dd</b>");
		req.setLocationState("浙江");
		req.setLocationCity("杭州");
		req.setCid(110209L);
		req.setProps("20000:11656;1748306:6759687;20879:32557;20638:21543;20849:32142;3782067:38404325;4077444:41723096;30681:32998;");
		*/
		req.setNum(Long.parseLong(item.getNum()));
		req.setPrice(item.getPrice());
		req.setType(item.getType());
//		req.setStuffStatus("new");
		req.setTitle(item.getTitle());

		// req8.setImage(new
		// FileItem("http://img04.tbsandbox.com/bao/uploaded/i4/T1updXXe..4t1e17oY_030240.jpg"));
		req.setImage(new FileItem(item.getPic_url()));
		req.setDesc(item.getDesc());
//		req.setLocationState();
//		req.setLocationCity("杭州");
		req.setCid(Long.parseLong(item.getCid()));
		req.setProps(item.getProps());
		
		ItemAddResponse response = client.execute(req, session);

		System.out.println(response.getBody());
	
		return response.getBody();
	}

	public String ItemDeleteRequest(long numiid) throws Exception {

		ItemDeleteRequest req = new ItemDeleteRequest();
		req.setNumIid(numiid);
		ItemDeleteResponse response = client.execute(req, session);
		System.out.println(response.getBody());
		return response.getBody();
	}

	/**
	 * 
	 * 获得用户信息。
	 * 
	 * @param nick
	 * @return
	 * @throws Exception
	 */
	public String UserGetReques(String nick) throws Exception {

		UserGetRequest req = new UserGetRequest();
		req.setFields("user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind");
		req.setNick(nick);
		UserGetResponse response = client.execute(req, session);
		System.out.println(response.getBody());
		return response.getBody();

	}

	/**
	 * 通过父类目列出所有的子类目，第一级为0
	 * 
	 * @param parent_cid
	 * @return
	 * @throws Exception
	 */
	public String ItemcatsGetRequest_p(long parent_cid) throws Exception {

		ItemcatsGetRequest req = new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent");
		req.setParentCid(parent_cid);
		ItemcatsGetResponse response = client.execute(req);
		System.out.println("ItemcatsGetRequest_p="+response.getBody());
		return response.getBody();

	}

	/**
	 * 列出指定类目id的属性
	 * 
	 * @param cid
	 * @return
	 * @throws Exception
	 */

	public String ItemcatsGetRequest_C(String cid) throws Exception {

		ItemcatsGetRequest req = new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent");
		req.setCids(cid);
		ItemcatsGetResponse response = client.execute(req);
		System.out.println("ItemcatsGetRequest_C="+response.getBody());
		return response.getBody();

	}

	/**
	 * 
	 * 获得指定cid的属性，可以通过3步获得指定型号的属性
	 * 
	 * 1.传入cid ，req.setCid(110219L); 获得pid 如20000l和vid 4534862
	 * 2.将pid作为req.setParentPid 的参数，传给req.setParentPid(20000L);通过之前的vid获得
	 * 找到parent_vid 值为4534862 的pid ，此时pid为5722879。
	 * "parent_vid":4534862,"pid":5722879, 3.通过设置 req.setCid(110219L);
	 * req.setPid(5722879L); req.setParentPid(20000L);
	 * 
	 * 获得产品的属性 req.setCid(110219L); req.setPid(5722879L);
	 * req.setParentPid(20000L);
	 * 
	 * 参数为-1则不设置
	 * @param cid
	 * @param pid
	 * @param parentpid
	 * @return
	 * @throws Exception
	 */
	public String ItempropsGetRequest(long cid, long pid, long parentpid)
			throws Exception {

		ItempropsGetRequest req = new ItempropsGetRequest();
		req.setFields("parent_pid,pid,parent_vid,name,prop_values,is_key_prop,is_input_prop");
		if(cid!=-1)
		req.setCid(cid);
		if(pid!=-1)
		req.setPid(pid);
		if(parentpid!=-1)
		req.setParentPid(parentpid);
//		 req.setCid(110219L);
		ItempropsGetResponse response = client.execute(req,session);
		System.out.println(response.getBody());
		return response.getBody();
	}

	/**
	 * 返回下一个级别类目的列表或者属性
	 * 如果不是叶子类目这返回下级的类目，否则返回属性。
	 * @param cid
	 * @return
	 * @throws Exception
	 */
	public String getNextCat(long cid) throws Exception {
		String p1 = ItemcatsGetRequest_p(cid);
		JSONObject jsonObject = JSONObject.fromObject(p1);
		System.out.println("js="+jsonObject);
		// System.out.println(jsonObject.getJSONObject("itemcats_get_response").getJSONObject("item_cats"));
		// System.out.println(jsonObject.getJSONObject("itemcats_get_response").getJSONObject("item_cats").getJSONArray("item_cat"));
		if (!jsonObject.getJSONObject("itemcats_get_response") .isNullObject()
				&& !jsonObject.getJSONObject("itemcats_get_response")
						.getJSONObject("item_cats").isNullObject()
				&& !jsonObject.getJSONObject("itemcats_get_response")
						.getJSONObject("item_cats").getJSONArray("item_cat").isEmpty()
				&&
				jsonObject.getJSONObject("itemcats_get_response")
						.getJSONObject("item_cats").getJSONArray("item_cat")
						.size() > 0) {
//			long cid_t = jsonObject.getJSONObject("itemcats_get_response")
//					.getJSONObject("item_cats").getJSONArray("item_cat")
//					.getJSONObject(0).getLong("cid");
//			//getNextCat(cid_t);
//			System.out.println(cid_t);
//			System.out.println(ItemcatsGetRequest_p(cid_t));
//			return ItemcatsGetRequest_p(cid_t);
			return jsonObject.toString();
		} else {
			System.out.println("this is last");
//			String p2 = ItemcatsGetRequest_C(cid+"");
			String p2 = ItempropsGetRequest(cid, -1,-1);
			System.out.println(p2);
			return p2;
		}
		
//		return null;
	}

	
	public String getkeyprops(long cid,String vid ) throws Exception
	{
		String pid_str = ItempropsGetRequest(cid, -1,-1);
		JSONObject jsonObject = JSONObject.fromObject(pid_str);
		JSONArray jsonarray = jsonObject.getJSONObject("itemprops_get_response").getJSONObject("item_props").getJSONArray("item_prop");

	for(int i=0;i<jsonarray.size();i++)
		{
//			System.out.println("  "+jsonarray.getJSONObject(i));
//			System.out.println("  "+jsonarray.getJSONObject(i).getString("pid"));
			//System.out.println("  "+jsonarray.getJSONObject(i).getString("vid"));
			if(jsonarray.getJSONObject(i).getBoolean("is_key_prop") &&
					jsonarray.getJSONObject(i).getBoolean("is_input_prop")  )
			{
				System.out.println("....");
				String pro2 = ItempropsGetRequest(cid, -1,jsonarray.getJSONObject(i).getLong("pid"));
				JSONObject jsonObject2 = JSONObject.fromObject(pro2);
				JSONArray jsonarray2  = jsonObject2.getJSONObject("itemprops_get_response").getJSONObject("item_props").getJSONArray("item_prop");
				for(int j=0;j<jsonarray2.size();j++)
				{
					if(jsonarray2.getJSONObject(j).getString("parent_vid").equals(vid)) //4534862
					{
						System.out.println("bingo");
						System.out.println(jsonarray2.getJSONObject(j));
						return jsonarray2.getJSONObject(j).toString();
					}
				}
			}
//			System.out.print("  "+jsonarray.getJSONObject(i).getString("multi"));
////			System.out.print("  "+jsonarray.getJSONObject(i).getString("must"));
//			System.out.print("  "+jsonarray.getJSONObject(i).getString("name"));
//		
//			System.out.println("  "+jsonarray.getJSONObject(i).getString("pid"));
			 
		}
	return null;
	}
	public static void main(String[] argv) throws Exception {
		String url = "http://gw.api.tbsandbox.com/router/rest";
		String appkey = "12277545";// 12277545 //12232777
		String secret = "sandbox4b9089895943bd89cad10154e";// "sandboxe090d9019eba130342d995ea7";
		String session = "";
		Actions action = new Actions(url, appkey, secret, session);
		/*
		 * action.ProductsGetRequest(); action.ItemsOnsaleGetRequest();
		 * action.UserGetReques("liuxiaozheng012");
		 * action.ItempropsGetRequest(110219L, 5722879L, 20000L);
		 */
//		action.getNextCat(0);
		//action.getNextCat(50011949);
		
		//action.getNextCat(50016161);
/*		String pid_str = action.ItempropsGetRequest(110219L, -1,-1);
		JSONObject jsonObject = JSONObject.fromObject(pid_str);
		JSONArray jsonarray = jsonObject.getJSONObject("itemprops_get_response").getJSONObject("item_props").getJSONArray("item_prop");

	for(int i=0;i<jsonarray.size();i++)
		{
			System.out.println("  "+jsonarray.getJSONObject(i));
			System.out.println("  "+jsonarray.getJSONObject(i).getString("pid"));
			//System.out.println("  "+jsonarray.getJSONObject(i).getString("vid"));
			if(jsonarray.getJSONObject(i).getBoolean("is_key_prop") &&
					jsonarray.getJSONObject(i).getBoolean("is_input_prop")  )
			{
				System.out.println("....");
				String pro2 = action.ItempropsGetRequest(110219L, -1,jsonarray.getJSONObject(i).getLong("pid"));
				JSONObject jsonObject2 = JSONObject.fromObject(pro2);
				JSONArray jsonarray2  = jsonObject2.getJSONObject("itemprops_get_response").getJSONObject("item_props").getJSONArray("item_prop");
				for(int j=0;j<jsonarray2.size();j++)
				{
					if(jsonarray2.getJSONObject(j).getString("parent_vid").equals("4534862"))
					{
						System.out.println("bingo");
						System.out.println(jsonarray2.getJSONObject(j));
					}
				}
			}
			
			
//			System.out.print("  "+jsonarray.getJSONObject(i).getString("multi"));
////			System.out.print("  "+jsonarray.getJSONObject(i).getString("must"));
//			System.out.print("  "+jsonarray.getJSONObject(i).getString("name"));
//		
//			System.out.println("  "+jsonarray.getJSONObject(i).getString("pid"));
		}*/
//	
	
//	action.ItempropsGetRequest(110219l, -1,-1);
//	action.ItemcatsGetRequest_p(110219l);
////	action.getkeyprops(110219l, "110219l");
//	action.ItemcatsGetRequest_C("110219");
	System.out.println(action.getNextCat(110219l));
	
	System.out.println(action.getkeyprops(110219l, "8940526"));
	
	}
}
